var UserApp = function () {
	return {
        init: function () {
        	UserApp.loadGrid();
        	UserApp.initPasswdForm();
        	UserApp.initAddForm();
    	},
    	savePasswd:function(){
    		$("#passwdForm").submit();
    	},
    	saveAddForm:function(){
	  		$("#addForm").submit();
	  	},
    	loadGrid:function(){
    		var url = $("#APP_ROOT_PATH").val() + 'user/page_data';
    		gui.widgets.BootStrap.loadGrid({
                gridSelector:"#grid-table",
                pagerSelector:"#grid-pager",
                postData:{
                	"nickName":function(){
                		return $.trim($("#nickName").val());
                	},
                	"phone":function(){
                		return $.trim($("#phone").val());
                	},
                	"account":function(){
                		return $.trim($("#account").val());
                	}
                },
                jsonReader : {
                    root: "data.rows",
                    records: "data.total",
                    repeatitems : false,
                    total: function (obj) {
                        return  Math.ceil(obj.data.total /jQuery("#grid-table").getGridParam("rowNum"));
                    }
                } ,
                datatype: 'json',
                url:url,
                colNames:['账号','姓名','手机','创建时间','操作'],
                colModel:[{name:'account'},
                          {name:'nickName'},
                          {name:'phone'},
                          {name:'gmtCreate'},
                    {name:'id',index:'id', width:200,formatter:function(cellvalue,options,rowObject){
                 	var html = '<a href="javascript:void(0)" onclick="UserApp.deleteUser(' + cellvalue + ')">删除</a>&nbsp;&nbsp;&nbsp;';
                    	html += '<a href="javascript:void(0)" onclick="UserApp.detail(' + cellvalue + ')">修改</a>&nbsp;&nbsp;&nbsp;';
                    	
                    	html += '<a href="javascript:void(0)" onclick="UserApp.resetPasswd(' + cellvalue + ')">重置密码</a>';
                    	return html;
                    }}
                ],
                caption: "用户信息",
                rowList:[10,20,30],
                multiselect: true,
                prmNames:{
                    page:"pageNum",
                    rows:"pageSize",
                    sort: "sortField",
                    order: "sortOrder",
                    search:"_search"
                }
            });
    	},
    	reload:function(){
    		jQuery("#grid-table").jqGrid('setGridParam',{page:1}).trigger("reloadGrid");
    	},
    	/**
    	 * 重置
    	 */
    	reset:function(){
    		$("#nickName").val('');
    		$("#account").val('');
    		$("#phone").val('');
    	},
    	/**
    	 * 删除用户
    	 */
    	deleteUser: function(id){  
    		if(confirm("确定要要删除该用户信息吗?")){
					var url = $("#APP_ROOT_PATH").val() + '/user/del_by_id';
					gui.util.Ajax.asyncGET(url,{id:id},function(res){
						if(res.ret != 0){
							$.gritter.add({
								title: '错误提示',
								text: res.message,
								class_name: 'gritter-error'
							});
							return;
						}
						
						if(res.data == true){
							UserApp.reload();
						}else{
							$.gritter.add({
								title: '错误提示',
								text: '删除失败',
								class_name: 'gritter-error'
							});
						}
					});
				}
    			return false;
    		},
    	initPasswdForm:function(){
    		$("#passwdForm").validate({
    			rules:{
    				passwd:{'required':true,'maxlength':20,'minlength':6},
    				confirmPasswd:{'required':true,'equalTo':'#passwd'}
    			},
    			success:"valid",
    			messages:{
    				passwd:{required:'密码不能为空',minlength:'密码长度不能小于6位',maxlength:'密码程度不能大于20位'},
    				confirmPasswd:{required:'确认密码不能为空',equalTo:'两次输入的密码不一致'}
    			},
    			errorPlacement: function(error, element) {
					var placement = $(element).parent('div').find('.error_place');
					placement.html('');
                    error.appendTo(placement);
				},
				submitHandler:function(form){
					UserApp.newPasswd();
	            }
    		});
    	},
    	resetPasswd:function(id){
    		$("#id").val(id);
    		$("#memoAlert").modal();
    	},
    	
    	/**
    	 * 重置密码按钮
    	 */
    	newPasswd:function(){
    		var id = $("#id").val();
    		var passwd = $("#passwd").val();
    		var confirmPasswd = $("#confirmPasswd").val();
    		//console.log("id="+id+","+"passwd="+passwd+","+"confirmPasswd="+confirmPasswd)
    		
    		var url = $("#APP_ROOT_PATH").val() + 'user/update_passwd';
    		var data = {'id':id,'passwd':passwd};
    		if(passwd==confirmPasswd){
    			gui.util.Ajax.asyncGET(url,data,function(res){
    				
    				if(res.ret > 0){
    					layer.msg(res.message, {icon : 2});
    					return false;
    				}
    				if(res.data == true){
    					layer.msg('成功', {
    						icon : 1
    					});
    					window.parent.location.reload();
    					return false;
    				}else if(res.data == false){
    					layer.msg('失败', {
    						icon : 0
    					});
    					window.parent.location.reload();
    					return false;
    				}
    			});
    		}
    	},
    	/**
    	 * 新增/修改
    	 */
    	detail:function(id){
    		var url;
    		if(id != undefined && id != null && id != "" && id != 'undefined'){
    			$("#userId").val(id);
    			url = $("#APP_ROOT_PATH").val() + 'user/detail?id=' + id;
    		}else{
    			url = $("#APP_ROOT_PATH").val() + 'user/detail';
    		}
    		$("#NoPermissioniframe").attr("src", url);
    		$("#createDialog").modal();
    	},
    	/**
    	 * 关闭按钮
    	 */
    	closed:function(){
    		window.parent.location.href= $("#APP_ROOT_PATH").val() + 'user/index';
    	},
    	
    	/**
    	 * 表单验证
    	 */
    	initAddForm:function(){
    		 // 手机号码验证    
		    jQuery.validator.addMethod("isMobile", function(value, element) {    
		      var length = value.length;    
		      return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value));    
		    }, "请正确填写您的手机号码。");
    		
    		var url = $("#APP_ROOT_PATH").val();
    		$("#addForm").validate({
    			rules:{
    				accountAdd:{'required':true,'minlength':3,'maxlength':20,remote:{
    					url: url + "user/query_account",     //后台处理程序
    				    type: "post",               //数据发送方式
    				    dataType: "json",           //接受数据格式   
    				    data: {                     //要传递的数据
    				        account: function() {
    				            return $.trim($("#accountAdd").val());
    				        },
    				        userId:function(){
    				        	return $.trim($("#userId").val());
    				        }
    				    },
    				    dataFilter: function (res) {
    				    	var res = eval('('+ res + ')');
    				    	if(res.ret != 0){
    				    		return false;
    				    	}
    				    	return res.data;
    				    }
    				}},
    				phoneAdd:{'required':true,'isMobile':true,remote:{
    					url: url + "user/query_phone",     //后台处理程序
    				    type: "post",               //数据发送方式
    				    dataType: "json",           //接受数据格式   
    				    data: {                     //要传递的数据
    				        phone: function() {
    				            return $.trim($("#phoneAdd").val());
    				        },
    				        userId:function(){
    				        	return $.trim($("#userId").val());
    				        }
    				    },
    				    dataFilter: function (res) {
    				    	var res = eval('('+ res + ')');
    				    	if(res.ret != 0){
    				    		return false;
    				    	}
    				    	
    				    	return res.data;
    				    }
    				}},
    				nickNameAdd:{'required':true,'maxlength':10},
    				passwdAdd:{'required':true,'maxlength':20,'minlength':6},
    				confirmPasswdAdd:{'required':true,'equalTo':'#passwdAdd'}
    			},
    			messages:{
    				accountAdd:{required:'账号不能为空',minlength:'账号不能小于3位',maxlength:'账号不能大于20位',remote:'该账号已经被使用了'},
    				phoneAdd:{required:'手机号码不能为空',isMobile:'手机号码格式不正确',remote:'该手机号码已被注册'},
    				nickNameAdd:{required:'姓名不能为空',maxlength:'姓名不能大于10个字'},
    				passwdAdd:{required:'密码不能为空',minlength:'密码长度不能小于6位',maxlength:'密码程度不能大于20位'},
    				confirmPasswdAdd:{required:'确认密码不能为空',equalTo:'两次输入的密码不一致'}
    			},
    			errorPlacement: function(error, element) {
					var placement = $(element).parent('div').find('.error_place');
					placement.html('');
                    error.appendTo(placement);
				},
				submitHandler:function(form){
					UserApp.saveAdd();
	            }
    		});
    	},
    	/**
    	 * 保存新用户
    	 */
    	saveAdd:function(){
    		var id = $("#userId").val();
    		var account = $.trim($("#accountAdd").val());
    		var phone = $.trim($("#phoneAdd").val());
    		var nickName = $.trim($("#nickNameAdd").val());
    		var passwd = $.trim($("#passwdAdd").val());
    		var confirmPasswdAdd = $.trim($("#confirmPasswdAdd").val());
    		
    		var url = $("#APP_ROOT_PATH").val() + 'user/save';
    		var data= {'id':id,'account':account,'phone':phone,'nickName':nickName,'passwd':passwd};
    			gui.util.Ajax.asyncGET(url,data,function(res){
    				
    				if(res.ret > 0){
    					layer.msg(res.message,{incon : 2})
    					return false;
    				}
    				
    				if(res.data == true){
    					layer.msg('成功', {icon : 1});
    					setTimeout(function(){
    						window.parent.location.reload();
    					},1000)
    					return false;
    				}else if(res.data == false){
    					layer.msg('失败', {
    						icon : 1
    					});
    					setTimeout(function(){
    						window.parent.location.reload();
    					},1000)
    					return false;
    				}
    			});
    	}
    }
}();